import { computed, reactive, ref } from 'vue'
import apis, { request } from '../apis/index.js'
import itf from '../utils/interface.js'

export default function useMessageCodeSender() {
  // 获取验证码剩余冷却时间
  const mcRequestCd = ref(0)

  // 判断获取验证码按钮是否冷却中（剩余冷却时间大于 0）
  const isMcRequestCd = computed(() => mcRequestCd.value > 0)

  // 获取验证码冷却定时器
  let mcRequestTimer = null

  // 是否正在调用接口
  const isLoading = ref(false)

  async function sendTo(phone, type) {
    if (mcRequestCd.value > 0) {
      throw new Error('请勿频繁获取验证码')
    }

    const reg = new RegExp('^1[0-9]{10}$')
    if (!reg.test(phone)) {
      throw new Error('手机号格式错误，请重新输入！')
    }

    itf.showLoading({
      title: '正在发送验证码',
    })
    isLoading.value = true

    const params = { phoneNum: phone , smsType : `${type}`}
    const optionalConfig = { disableToken: true }

    try {
      // await request.get(apis[`sendSmsBy${type}`], params, optionalConfig)
      await request.get(apis.sendVerifySms, params, optionalConfig)

      mcRequestCd.value = 60
      mcRequestTimer = setInterval(() => {
        mcRequestCd.value -= 1

        if (mcRequestCd.value <= 0) {
          mcRequestCd.value = 0
          clearInterval(mcRequestTimer)
          mcRequestTimer = null
        }
      }, 1000)
    } catch (err) {
      throw new Error(err.message)
    } finally {
      itf.hideLoading()
      isLoading.value = false
    }
  }

  return reactive({
    mcRequestCd,
    isMcRequestCd,
    sendTo,
    isLoading,
  })
}
